package com.blog.quartz;

import com.blog.bean.domain.ViewCountLog;
import com.blog.exception.ServiceException;
import com.blog.mapper.DiscussPostMapper;
import com.blog.mapper.ViewCountLogMapper;
import com.blog.bean.vo.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Set;

/**
 * @author 任浩
 * @version 1.0
 *
 *
 * 这是对浏览量更新到数据库的定时任务，使用quartz进行定时任务更新。
 */

@Slf4j
//@Component
public class ViewCountJob implements Job {

    @Resource
    private RedisUtils redisUtils;

    @Autowired
    private DiscussPostMapper discussPostMapper;

    @Autowired
    private ViewCountLogMapper viewCountLogMapper;

    /**
     * 这是quartz执行调度任务的具体操作。
     * @param jobExecutionContext
     * @throws JobExecutionException
     */
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        log.info("浏览量定时任务开启执行");
        //首先匹配出来所有的redis里面存储的浏览量的key。
        Set<String> keys = redisUtils.patternKeys("viewCount:*");
        log.info("查询出来的keys为：" + keys);

        if(keys.isEmpty()){
            log.info("没有浏览量数据可以更新。");
            return;
        }
        ViewCountLog viewCountLog = new ViewCountLog();

        //然后根据读取出来的key，把浏览量存储到数据库中，最后再把当前的redis key删除。
        keys.forEach(s ->{
            //开始执行任务的时间
            long start = System.currentTimeMillis();
            Integer viewCount = null;
            Integer postId = null;
            try {
                //从缓存中得到浏览量
                viewCount = redisUtils.getViewCount(s);
                log.info("{} 浏览量为: {}",s,viewCount);
                //对key进行拆分得到id
                String[] split = s.split(":");
                postId = Integer.parseInt(split[1]);
                log.info("拆分的数据得到的id为：" + postId);
                //到数据库更新浏览量
                discussPostMapper.updateViewCount(postId,viewCount);
                log.info("定时任务更新成功");

                viewCountLog.setPostId(postId);
                viewCountLog.setViewCount(viewCount);
                viewCountLog.setViewStatus(1);
            }
            catch (Exception e){
                viewCountLog.setPostId(postId == null ? 0 : postId);
                viewCountLog.setViewCount(viewCount == null ? 0 : viewCount);
                viewCountLog.setViewStatus(2);
            }
            finally {
                //插入成功之后，把存储在redis中的数据删除。
                redisUtils.deleteViewCount(s);
                log.info("删除缓存中的数据成功");
                long end = System.currentTimeMillis();

                Long tmpTime = (end-start);
                Integer time = tmpTime.intValue();
                log.info("更新浏览量定时任务执行时间：" + time);
                viewCountLog.setTime(time);
                viewCountLog.setCreateTime(LocalDateTime.now());

                int insert = viewCountLogMapper.insert(viewCountLog);
                if (insert != 1){
                    log.info("插入浏览量定时任务失败");
                    throw new ServiceException("插入浏览量定时任务失败");
                }
            }
        });
    }
}
